using Digitalmes.Domain.Entities.Mes.Productions;

namespace Digitalmes.Application.Mes.Productions.WorkOrders.Queries;

/// <summary>
/// 工单序列分页查询命令
/// </summary>
public sealed record GetSequenceWorkOrderListWithPagedQuery(
    string? Wo,
    int PageNumber,
    int PageSize) : IPagedQuery, IRequest<IResult<PagedList<ProdWorkOrderDto>>>;

internal sealed class GetSequenceWorkOrderListWithPagedQueryHandler(IRepository<ProdWorkOrder> repo)
    : IRequestHandler<GetSequenceWorkOrderListWithPagedQuery, IResult<PagedList<ProdWorkOrderDto>>>
{
    public async Task<IResult<PagedList<ProdWorkOrderDto>>> Handle(GetSequenceWorkOrderListWithPagedQuery request, CancellationToken cancellationToken)
    {
        WoStatusEnum[] statuns = [WoStatusEnum.Scheduled, WoStatusEnum.InProgress, WoStatusEnum.OnHold, WoStatusEnum.Completed];
        var items = await repo.AsQueryable()
            .Includes(m => m.Product)
            .Includes(m => m.Line)
            .WhereIF(!string.IsNullOrWhiteSpace(request.Wo), m => m.Wo.Contains(request.Wo!))
            .Where(m => statuns.Contains(m.Status))
            .OrderBy(m => m.Priority)
            .GetPagedListAsync(request.PageNumber, request.PageSize, cancellationToken);
        return Result.From(items.Adapt<PagedList<ProdWorkOrderDto>>());
    }
}
